<template>
  <view class="leave-container">
    <uni-forms ref="form" :model="form" :rules="rules">
      <view class="form-card">
        <view class="card-header">
          <text class="header-title">请假申请</text>
        </view>
        
        <view class="card-content">
          <uni-forms-item name="leaveType" label="请假类型">
            <uni-data-select
              v-model="form.leaveType"
              :localdata="leaveTypeOptions"
              placeholder="请选择请假类型"
            />
          </uni-forms-item>
          
          <uni-forms-item name="startTime" label="开始时间">
            <uni-datetime-picker 
              type="datetime" 
              v-model="form.startTime" 
              :clear-icon="false"
              placeholder="请选择开始时间"
            />
          </uni-forms-item>
          
          <uni-forms-item name="endTime" label="结束时间">
            <uni-datetime-picker 
              type="datetime" 
              v-model="form.endTime" 
              :clear-icon="false"
              placeholder="请选择结束时间"
            />
          </uni-forms-item>
          
          <uni-forms-item name="reason" label="请假原因">
            <uni-easyinput 
              v-model="form.reason" 
              placeholder="请输入请假原因"
              type="textarea"
            />
          </uni-forms-item>
        </view>
      </view>
      
      <view class="action-buttons">
        <button type="primary" @click="submitForm">提交申请</button>
        <button type="default" @click="cancel">取消</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import { applyLeave } from "@/api/system/attendance";

export default {
  name: "AttendanceLeave",
  data() {
    return {
      // 表单参数
      form: {
        leaveType: 'personal',
        startTime: '',
        endTime: '',
        reason: ''
      },
      // 请假类型选项
      leaveTypeOptions: [
        { text: '事假', value: 'personal' },
        { text: '病假', value: 'sick' },
        { text: '年假', value: 'annual' },
        { text: '调休', value: 'compensatory' },
        { text: '其他', value: 'other' }
      ],
      // 表单校验
      rules: {
        leaveType: {
          rules: [{
            required: true,
            errorMessage: '请选择请假类型'
          }]
        },
        startTime: {
          rules: [{
            required: true,
            errorMessage: '请选择开始时间'
          }]
        },
        endTime: {
          rules: [{
            required: true,
            errorMessage: '请选择结束时间'
          }, {
            validateFunction: (rule, value, data, callback) => {
              if (new Date(value) <= new Date(data.startTime)) {
                callback('结束时间必须大于开始时间');
              }
              return true;
            }
          }]
        },
        reason: {
          rules: [{
            required: true,
            errorMessage: '请输入请假原因'
          }]
        }
      }
    };
  },
  created() {
    // 初始化表单数据
    this.initFormData();
  },
  mounted() {
    // 确保组件加载后表单项能正确初始化
    setTimeout(() => {
      if (this.$refs.form) {
        this.$refs.form.setRules(this.rules);
      }
    }, 300);
  },
  methods: {
    // 初始化表单数据
    initFormData() {
      this.form.startTime = this.getCurrentDateTime();
      this.form.endTime = this.getEndDateTime();
      console.log('初始化数据:', this.form);
    },
    
    // 表单提交
    submitForm() {
      this.$refs.form.validate().then(res => {
        console.log('表单验证结果:', res);
        
        if (res) {
          this.$modal.loading("提交中");
          
          // 准备提交的数据
          const submitData = {
            leaveType: this.form.leaveType,
            startTime: this.form.startTime,
            endTime: this.form.endTime,
            reason: this.form.reason
          };
          
          console.log('准备提交的数据:', submitData);
          
          applyLeave(submitData)
            .then(res => {
              this.$modal.closeLoading();
              console.log('提交响应:', res);
              
              if (res && res.code === 200) {
                // 使用正确的成功提示方法
                uni.showToast({
                  title: "申请提交成功",
                  icon: "success",
                  duration: 2000
                });
                
                // 返回上一页
                setTimeout(() => {
                  this.$tab.navigateBack();
                }, 1500);
              } else {
                this.$modal.showError((res && res.msg) || "申请提交失败");
              }
            })
            .catch(err => {
              console.error("请假申请失败:", err);
              this.$modal.closeLoading();
              this.$modal.showError("网络错误，请稍后重试");
            });
        } else {
          console.log('表单验证失败:', this.form);
          uni.showToast({
            title: "请完善表单信息",
            icon: "none",
            duration: 2000
          });
        }
      }).catch(error => {
        console.error('表单验证错误:', error);
        uni.showToast({
          title: "表单验证错误，请检查填写的内容",
          icon: "none",
          duration: 2000
        });
      });
    },
    
    // 取消按钮
    cancel() {
      this.$tab.navigateBack();
    },
    
    // 获取当前日期时间
    getCurrentDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = (now.getMonth() + 1).toString().padStart(2, '0');
      const day = now.getDate().toString().padStart(2, '0');
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      const seconds = now.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    
    // 获取默认结束时间（当前时间+8小时）
    getEndDateTime() {
      const now = new Date();
      now.setHours(now.getHours() + 8);
      const year = now.getFullYear();
      const month = (now.getMonth() + 1).toString().padStart(2, '0');
      const day = now.getDate().toString().padStart(2, '0');
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      const seconds = now.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
  }
};
</script>

<style lang="scss" scoped>
.leave-container {
  padding: 15px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.form-card {
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
  
  .card-header {
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
    margin-bottom: 15px;
    
    .header-title {
      font-size: 18px;
      font-weight: bold;
    }
  }
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  
  button {
    width: 48%;
    height: 45px;
    font-size: 16px;
  }
}
</style> 